/**
 * Copyright (c) 2012, lincomb Technology CO,LDT. All rights reserved.
 * Module: 债权转让申请
 * File: DebtAssignmentServiceImpl.java
 * Purpose: 处理债权转让申请Service实现层
 * Date: 2016-5-9
 */
package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.CommonUtilsDao;
import com.edais.dao.DebtAssignmentDao;
import com.edais.domain.AssignRule;
import com.edais.service.DebtAssignmentService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DateUtil;
import com.edais.util.Message;
import com.edais.vo.AssignRuleVo;
/**
 * ClassName: DebtAssignmentServiceImpl 
 * @Description: 债权转让申请Service实现类
 * @author ZuoJun
 * @date 2016-5-9 10:50:29
 */
@Service

@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class DebtAssignmentServiceImpl implements DebtAssignmentService {
	
	private static final Log logger = LogFactory.getLog(DebtAssignmentServiceImpl.class);
	
	@Autowired
	private DebtAssignmentDao debtAssignmentDao; 
	
	@Autowired
	private CommonUtilsDao commonUtilsDao;

	/**
	 * @Description: 处理债权转让申请业务
	 * @param params
	 * @return Map<String, Object>
	 * @author ZuoJun
	 * @date 2016-5-9 11:49:39
	 */
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	@Override
	public Map<String, Object> requestDebtAssignment(Map<String, Object> params) throws Exception {
		logger.info("------------------------------- DebtAssignmentServiceImpl requestDebtAssignment() start -------------------------------");
		Map<String, Object> rtnMap = new HashMap<String, Object>();
		//调用核心Code
		String transCode = "E370001";
		
		logger.info("------------------------------- DebtAssignmentServiceImpl requestDebtAssignment() transCode=" + transCode + " -------------------------------");
		
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, (String)params.get("userId"), params);
		
		logger.info("------------------------------- DebtAssignmentServiceImpl requestDebtAssignment() jsonStr=" + jsonStr + " -------------------------------");
		
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		
		logger.info("------------------------------- DebtAssignmentServiceImpl requestDebtAssignment() rtnStr=" + rtnStr + " -------------------------------");
		
		
		
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		
		if(jsonObject == null){
			rtnMap.put(Consts.RES_CODE, Consts.ERROR_CODE);
			rtnMap.put(Consts.RES_MSG, Consts.ErrorMsg.MSG00001);
			rtnMap.put(Consts.RES_MSG_CN, Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return rtnMap;
		}
		
		logger.info("[核心接口码] transCode=" + transCode);
		logger.info("rescode：" + jsonObject.getString(Consts.RES_CODE) + "；  resmsg：" + jsonObject.getString(Consts.RES_MSG));
		
		if(Consts.SUCCESS_CODE.equals(jsonObject.get(Consts.RES_CODE))){					
			// 设置返回code
			rtnMap.put(Consts.RES_CODE, Consts.SUCCESS_CODE);
			rtnMap.put(Consts.RES_MSG, Consts.SUCCESS_DESCRIBE);
			rtnMap.put(Consts.RES_MSG_CN, jsonObject.get(Consts.RES_MSG));
		}else{
			
			rtnMap.put(Consts.RES_CODE, jsonObject.get(Consts.RES_CODE));
			rtnMap.put(Consts.RES_MSG, jsonObject.get(Consts.RES_MSG));
			rtnMap.put(Consts.RES_MSG_CN, jsonObject.get(Consts.RES_MSG));
		}
						
		logger.info("------------------------------- DebtAssignmentServiceImpl requestDebtAssignment() end -------------------------------");
		
		return rtnMap;
	}
	
	
	/**
	 * 查询债权转让利率信息
	 */	 
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	@Override
	public String getDebtAssignmentRate(Map<String, Object> params) {
		
		String result = "";		
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		List<AssignRuleVo> rtnList = new ArrayList<AssignRuleVo>();
		
		//获取数据库系统时间
		String systemTime = commonUtilsDao.getSystemTime();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date systemDate = null;
		try {
			systemDate = df.parse(systemTime);
		} catch (ParseException e) {
			resultMap.put("list", new ArrayList());
			result = CommonUtil.setResultStringCn(resultMap, Consts.ERROR_CODE, "", "数据库系统时间转换异常!" + CommonUtil.printStackTraceToString(e));
			e.printStackTrace();
			return result;
		}
		//起息日期
		String investDateStr = String.valueOf(params.get("investDate"));		
		Date investDate = null;
		try {
			investDate = df.parse(investDateStr);
		} catch (ParseException e) {
			resultMap.put("list", new ArrayList());
			result = CommonUtil.setResultStringCn(resultMap, Consts.CHECK_CODE, "", "起息日期转换异常!" + CommonUtil.printStackTraceToString(e));
			e.printStackTrace();
			return result;
		}
				      
		//相差月数
		int months = DateUtil.getMonths(systemDate, investDate);
		
		
		logger.info("---------------------/debt/getDebtAssignmentRate DebtAssignmentServiceImpl getDebtAssignmentRate() systemTime=" + systemTime + " , investDateStr=" + investDateStr 
				+ " , months=" + months + "--------------------------");
		
		if(months < 3){
			resultMap.put("list", new ArrayList());
			result = CommonUtil.setResultStringCn(resultMap, Consts.ERROR_CODE, "", "您的投资未满3个月，还不能申请债权转让!");
			return result;
		}
		
        //转让时已持有期数
        long assignExpirs = 0;
        
        if(months >= 9){
        	assignExpirs = 9;
        }else if(months >= 6){
        	assignExpirs = 6;
        }else if(months >= 3){
        	assignExpirs = 3;
        }else if(months < 3){
        	resultMap.put("list", new ArrayList());
			result = CommonUtil.setResultStringCn(resultMap, Consts.ERROR_CODE, "", "未查询到债权转让利率规则数据! 起息日期与当前日期相差不能小于3个月!" + investDateStr);
			return result;
        }
       
        params.put("assignExpirs", assignExpirs);
        
        AssignRule assignRule = debtAssignmentDao.getDebtAssignmentRateInfo(params);
        
        if(assignRule == null){
        	resultMap.put("list", new ArrayList());
			result = CommonUtil.setResultStringCn(resultMap, Consts.ERROR_CODE, "", "未查询到债权转让利率规则数据!");
			return result;
        }    
               
        int day = 0;
		try {
			day = CommonUtil.daysBetween(investDateStr, systemTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
             
        float days = (day + 1)/365f;
        //投资本金
        String investAmount = String.valueOf(params.get("investAmount"));
        BigDecimal assignAmount = new BigDecimal(investAmount);
        
        //起息年化天数((转让申请日-起息日)/365)
        BigDecimal valueDateRate = new BigDecimal(days);
        //转让手续费的计算公式为:（【转让人投资本金】+【转让人投资本金】X【转让年化收益率】X（转让申请日-起息日）/365）X手续费率
        
   
        BigDecimal  assignFee = assignAmount.add(
        				assignAmount.multiply(assignRule.getAnnualRate().add(assignRule.getCouponsRate()))//年化利率 + 加息利率
						.multiply(valueDateRate))
						.multiply(assignRule.getAssignFeeRate());
                
        //设置返回数据
        AssignRuleVo assignRuleVo = new AssignRuleVo();
        assignRuleVo.setAnnualRate(assignRule.getAnnualRate().add(assignRule.getCouponsRate()).multiply(new BigDecimal("100")));//债权转让利率(年化利率 + 加息利率)(已转化为百分数的值)
        assignRuleVo.setRateDesc(assignRule.getRateDesc());//债权转让利率描述
        
        DecimalFormat decimalFormat = new DecimalFormat("0.00"); 
        
        String assignFeeStr = decimalFormat.format(assignFee.setScale(2, BigDecimal.ROUND_DOWN));
        double assignFeeDigital = Double.parseDouble(assignFeeStr);
        if(assignFeeDigital == 0){
        	assignFeeStr = "0";
        }
        
        assignRuleVo.setAssignFee(assignFeeStr);//债权转让手续费
        assignRuleVo.setAssignFeeDesc(assignRule.getAssignFeeDesc());//债权转让手续费描述
        assignRuleVo.setAssignRuleDesc(assignRule.getAssignRuleDesc());//债权转让规则描述
        rtnList.add(assignRuleVo);//年化利率 + 加息利率
       		
		
		resultMap.put("list", rtnList);
		result = CommonUtil.setResultStringCn(resultMap, Consts.SUCCESS_CODE, "", "获取债权转让利率信息成功!");
		
		logger.info("---------------------/debt/getDebtAssignmentRate DebtAssignmentServiceImpl getDebtAssignmentRate() systemTime=" + systemTime + " , investDateStr=" + investDateStr 
				+ " ,assignExpirs=" + assignExpirs + " , days=" + days + " , assignFee=" + assignFee.toString() + "--------------------------");
		
		return result;
	}

}
